﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：x
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using System;
using Dapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.Repositores;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace seejee_Backendium.Data.Services
{
    public class ChartService : IChartService
    {
        private readonly string _connectionString;
        private readonly ILogger<ChartService> _logger;
        private readonly ChartDataRepository _chartdatarepository;

        public ChartService(IConfiguration config, ILogger<ChartService> logger,ChartDataRepository chartdatarepository)
        {
            _connectionString = config.GetConnectionString("Default");
            _logger = logger;
            _chartdatarepository = chartdatarepository;
        }

        public async Task<int> SaveBIMainTableAsync(string name, string createdAt, string cusName)
        {
            const string sql = @"
        INSERT INTO SEBI_BIMainTable (Name, CreatedAt, CusName)
        OUTPUT INSERTED.Id
        VALUES (@Name, @CreatedAt, @CusName)";

            try
            {
                using var connection = new SqlConnection(_connectionString);
                return await connection.ExecuteScalarAsync<int>(sql, new
                {
                    Name = name,
                    CreatedAt = DateTime.Parse(createdAt),
                    CusName = cusName
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存主表失败 | Name: {Name}, CusName: {CusName}", name, cusName);
                throw;
            }
        }

        public async Task<bool> SaveFlipNumberConfigAsync(
            string itemId, string type, int span, int height,
            string title, string titleColor, int titleSize,
            string valueColor, int valueSize, string unit, int unitSize,
            string iconImage, string iconColor, string iconSize, string ringColor, string ringValue, string iconPosition, bool thousandSeparator, string cusName , int bIMainTableId,
            string backgroundColor, string backgroundStyle, string leftunit, string leftunitsize,int sort, string sql)
        {
            // SQL语句字段严格匹配表结构：id（自增主键）、cId、type、span等
            const string sqlCommand = @"
        INSERT INTO SEBI_FlipNumberConfig (
            cId,         -- 图表项ID（对应itemId）
            type,        -- 图表类型
            span,        -- 宽度占比
            height,      -- 高度
            titleName,   -- 标题名称
            titleColor,  -- 标题颜色
            titleSize,   -- 标题大小
            valueColor,  -- 数值颜色
            valueSize,   -- 数值大小
            unit,        -- 单位
            unitSize,    -- 单位大小
            iconimage,   -- 图标（表中字段是iconimage，而非iconImage）
            iconColor,   -- 图标颜色
            iconSize,   -- 图标大小
            ringColor,  -- 圆环颜色
            ringValue,  -- 圆环文本
            iconPosition,-- 图标位置
            thousandSeparator, -- 千分位分隔符
            cSql,        -- SQL语句
            CusName,    -- 新增：用户名（根据实际业务补充，此处用默认值）
            sort,         -- 新增：排序号（根据实际业务补充，此处用默认值）
            BIMainTableId,   --关联主表id 
            backgroundColor,  -- 背景颜色
            backgroundStyle,   -- 背景央视
            leftunit,
            leftunitsize
        ) VALUES (
            @ItemId, 
            @Type, 
            @Span, 
            @Height, 
            @Title, 
            @TitleColor, 
            @TitleSize, 
            @ValueColor, 
            @ValueSize, 
            @Unit,
            @UnitSize, 
            @IconImage,
            @IconColor,
            @IconSize,
            @RingColor,
            @RingValue,
            @IconPosition, 
            @ThousandSeparator, 
            @Sql,
            @cusName,   -- 新增参数
            @Sort,        -- 新增参数
            @BIMainTableId,
            @BackgroundColor, 
            @BackgroundStyle,
            @Leftunit,
            @Leftunitsize
        )";

            try
            {
                using var connection = new SqlConnection(_connectionString);
                var affectedRows = await connection.ExecuteAsync(sqlCommand, new
                {
                    ItemId = itemId,
                    Type = type,
                    Span = span,
                    Height = height,
                    Title = title,
                    TitleColor = titleColor,
                    TitleSize = titleSize,
                    ValueColor = valueColor,
                    ValueSize = valueSize,
                    Unit = unit,
                    UnitSize = unitSize,
                    IconImage = iconImage,  // 映射到表中的iconimage字段
                    IconColor = iconColor,
                    IconSize = iconSize,
                    RingColor = ringColor,       
                    RingValue = ringValue,   
                    IconPosition = iconPosition,
                    ThousandSeparator = thousandSeparator,
                    Sql = sql,
                    CusName = cusName,   // 用户名：根据实际业务设置（如当前登录用户）
                    BackgroundColor = backgroundColor,  // 赋值新参数
                    BackgroundStyle = backgroundStyle,  // 赋值新参数
                    Sort = sort,               // 排序号：默认0，可根据业务调整
                    BIMainTableId = bIMainTableId,  // 传入主表id
                    Leftunit = leftunit,
                    Leftunitsize = leftunitsize
                });

                return affectedRows > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存FlipNumberConfig失败 | ID: {ItemId}", itemId);
                throw;
            }
        }

        public async Task<Dictionary<string, object>> ProcessAndSaveChartDataAsync(JObject jsonData)
        {
            var result = new Dictionary<string, object>();

            try
            {
                // 1. 保存主表
                var cusName = jsonData["cusName"]?.ToString();
                var mainTableId = await SaveBIMainTableAsync(
                    jsonData["name"]?.ToString(),
                    jsonData["createdAt"]?.ToString(),
                    jsonData["cusName"]?.ToString()
                );
                result.Add("mainTableId", mainTableId);

                // 2. 处理items
                if (jsonData["items"] is JArray items)
                {
                    var flipItems = items.Where(i => i["type"]?.ToString() == "flopwithicon");
                    var savedItems = new List<string>();
                    int sortCounter = 1; // 初始化计数器
                    foreach (var item in flipItems)
                    {
                        await SaveFlipNumberConfigAsync(
                            itemId: item["id"]?.ToString(),
                            type: item["type"]?.ToString(),
                            span: item["span"]?.ToObject<int>() ?? 0,
                            height: item["height"]?.ToObject<int>() ?? 0,
                            title: item["title"]?.ToString(),
                            titleColor: item["titleColor"]?.ToString() ?? "black",
                            titleSize: item["titleSize"]?.ToObject<int>() ?? 16,
                            valueColor: item["valueColor"]?.ToString() ?? "black",
                            valueSize: item["valueSize"]?.ToObject<int>() ?? 16,
                            unit: item["unit"]?.ToString(),
                            unitSize: item["unitSize"]?.ToObject<int>() ?? 16,
                            iconImage: item["iconimage"]?.ToString(),
                            iconColor: item["iconColor"]?.ToString(),
                            iconSize: item["iconSize"]?.ToString(),
                            ringColor: item["ringColor"]?.ToString(),
                            ringValue: item["ringValue"]?.ToString(),
                            iconPosition: item["iconPosition"]?.ToString() ?? "left",
                            thousandSeparator: item["thousandSeparator"]?.ToObject<bool>() ?? true,
                            backgroundColor: item["backgroundColor"]?.ToString(),
                            backgroundStyle: item["backgroundStyle"]?.ToString(),
                            leftunit: item["leftunit"]?.ToString(),
                            leftunitsize: item["leftunitsize"]?.ToString(),
                            cusName: cusName,  // 补充传递cusName参数
                            bIMainTableId: mainTableId,  // 传递主表id
                            sort: sortCounter,
                            sql: (item["sqlList"] as JArray)?.First?.ToString()
                        );
                        savedItems.Add(item["id"]?.ToString());
                        sortCounter++; // 递增
                    }

                    result.Add("savedItems", savedItems);
                }

                result.Add("success", true);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理图表数据失败");
                result.Add("error", ex.Message);
                result.Add("success", false);
                return result;
            }
        }

        public async Task<string> GetDashboardConfigAsync()
        {
            // 调用仓储层从数据库获取原始JSON
            return await _chartdatarepository.GetConfigJsonAsync();
        }
        public async Task<LineDataDTO> GetLineData(string cCusName, string cCusTableName, string xAxis, string yAxis)
        {
            // 调用仓储层从数据库获取原始JSON
            return await _chartdatarepository.GetLineData(cCusName, cCusTableName, xAxis, yAxis);
        }
        public async Task<string> RenderChartAsync(List<string> sqlList)
        {
            return await _chartdatarepository.RenderChartAsync(sqlList);
        }
    }

}